package cn.gjxblog.core.social.qq.provider.api;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.social.oauth2.AbstractOAuth2ApiBinding;
import org.springframework.social.oauth2.TokenStrategy;

import java.io.IOException;

/**
 * @author gjx
 * @version v1.0
 * @Description
 * @date 2019/1/17 16:03
 */
public class QQImpl extends AbstractOAuth2ApiBinding implements QQ  {

    private Logger logger = LoggerFactory.getLogger(QQImpl.class);

    private static final String URL_GET_OPENID = "https://graph.qq.com/oauth2.0/me?access_token=%s";
    private static final String URL_GET_USER_INFO ="https://graph.qq.com/user/get_user_info?oauth_consumer_key=%s&openid=%s";

    private String appId;//申请QQ登录成功后，分配给应用的appid
    private String openId;//用户的ID，与QQ号码一一对应

    private ObjectMapper objectMapper = new ObjectMapper();

    public QQImpl(String accessToken, String appId) {
        super(accessToken,TokenStrategy.ACCESS_TOKEN_PARAMETER);

        this.appId =appId;

        String url = String.format(URL_GET_OPENID,accessToken);
        String result = getRestTemplate().getForObject(url, String.class);

        logger.info(result);

        openId = StringUtils.substringBetween(result, "\"openid\":\"", "\"}");


    }



    @Override
    public QQUser getUser() {
        String url = String.format(URL_GET_USER_INFO,appId,openId);
        String result = getRestTemplate().getForObject(url, String.class);
        logger.info(result);
        QQUser qqUser = null;
        try {
            qqUser = objectMapper.readValue(result, QQUser.class);
            qqUser.setOpenId(openId);//
        } catch (IOException e) {
            e.printStackTrace();
        }
        return qqUser;
    }
}
